from fastapi import APIRouter, Depends, HTTPException, status
from sqlalchemy.ext.asyncio import AsyncSession
from typing import List, Optional

from app.core.database import get_db
from app.core.deps import get_current_user, get_tenant_id
from app.schemas.menu import (
    MenuQuery, MenuVO, MenuForm, MenuTreeOption, RoleMenuTree
)
from app.models.user import User
# from app.services.menu import menu_service
from app.utils.response import ResponseUtil

router = APIRouter()


@router.get("/list", summary="查询菜单列表", response_model=List[MenuVO])
async def list_menu(
    query: Optional[MenuQuery] = Depends(),
    db: AsyncSession = Depends(get_db),
    tenant_id: str = Depends(get_tenant_id)
):
    """查询菜单列表"""
    menus = await menu_service.get_menu_list(db, query=query, tenant_id=tenant_id)
    return menus


@router.get("/{menuId}", summary="查询菜单详细", response_model=MenuVO)
async def get_menu(
    menuId: int,
    db: AsyncSession = Depends(get_db),
    tenant_id: str = Depends(get_tenant_id)
):
    """查询菜单详细"""
    menu = await menu_service.get_menu_by_id(db, menu_id=menuId, tenant_id=tenant_id)
    if not menu:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="菜单不存在"
        )
    return menu


@router.get("/treeselect", summary="查询菜单下拉树结构", response_model=List[MenuTreeOption])
async def treeselect(
    db: AsyncSession = Depends(get_db),
    tenant_id: str = Depends(get_tenant_id)
):
    """查询菜单下拉树结构"""
    menu_tree = await menu_service.get_menu_tree_select(db, tenant_id=tenant_id)
    return menu_tree


@router.get("/roleMenuTreeselect/{roleId}", summary="根据角色ID查询菜单下拉树结构", response_model=RoleMenuTree)
async def role_menu_treeselect(
    roleId: int,
    db: AsyncSession = Depends(get_db),
    tenant_id: str = Depends(get_tenant_id)
):
    """根据角色ID查询菜单下拉树结构"""
    role_menu_tree = await menu_service.get_role_menu_tree(db, role_id=roleId, tenant_id=tenant_id)
    return role_menu_tree


@router.get("/tenantPackageMenuTreeselect/{packageId}", summary="根据租户套餐查询菜单下拉树结构", response_model=RoleMenuTree)
async def tenant_package_menu_treeselect(
    packageId: int,
    db: AsyncSession = Depends(get_db),
    tenant_id: str = Depends(get_tenant_id)
):
    """根据租户套餐查询菜单下拉树结构"""
    package_menu_tree = await menu_service.get_tenant_package_menu_tree(
        db, package_id=packageId, tenant_id=tenant_id
    )
    return package_menu_tree


@router.post("", summary="新增菜单")
async def add_menu(
    data: MenuForm,
    db: AsyncSession = Depends(get_db),
    current_user: User = Depends(get_current_user),
    tenant_id: str = Depends(get_tenant_id)
):
    """新增菜单"""
    new_menu = await menu_service.create_menu(db, menu_data=data, tenant_id=tenant_id)
    return ResponseUtil.success(data={"menuId": new_menu.menu_id}, message="菜单创建成功")


@router.put("", summary="修改菜单")
async def update_menu(
    data: MenuForm,
    db: AsyncSession = Depends(get_db),
    current_user: User = Depends(get_current_user),
    tenant_id: str = Depends(get_tenant_id)
):
    """修改菜单"""
    updated_menu = await menu_service.update_menu(
        db,
        menu_id=data.menuId,
        menu_data=data,
        tenant_id=tenant_id
    )
    if not updated_menu:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="菜单不存在"
        )
    return ResponseUtil.success(message="菜单更新成功")


@router.delete("/{menuId}", summary="删除菜单")
async def del_menu(
    menuId: int,
    db: AsyncSession = Depends(get_db),
    current_user: User = Depends(get_current_user),
    tenant_id: str = Depends(get_tenant_id)
):
    """删除菜单"""
    # 检查是否有子菜单
    has_children = await menu_service.has_children(db, menu_id=menuId, tenant_id=tenant_id)
    if has_children:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail="存在子菜单，不允许删除"
        )

    # 检查是否被角色使用
    is_used_by_role = await menu_service.is_used_by_role(db, menu_id=menuId, tenant_id=tenant_id)
    if is_used_by_role:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail="菜单已分配给角色，不允许删除"
        )

    deleted = await menu_service.delete_menu(db, menu_id=menuId, tenant_id=tenant_id)
    if not deleted:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="菜单不存在"
        )
    return ResponseUtil.success(message="菜单删除成功")


@router.delete("/cascade/{menuIds}", summary="级联删除菜单")
async def cascade_del_menu(
    menuIds: str,
    db: AsyncSession = Depends(get_db),
    current_user: User = Depends(get_current_user),
    tenant_id: str = Depends(get_tenant_id)
):
    """级联删除菜单"""
    menu_id_list = [int(mid.strip()) for mid in menuIds.split(',') if mid.strip()]

    # 检查是否被角色使用
    for menu_id in menu_id_list:
        is_used_by_role = await menu_service.is_used_by_role(db, menu_id=menu_id, tenant_id=tenant_id)
        if is_used_by_role:
            raise HTTPException(
                status_code=status.HTTP_400_BAD_REQUEST,
                detail=f"菜单 {menu_id} 已分配给角色，不允许删除"
            )

    deleted_count = await menu_service.cascade_delete_menus(db, menu_ids=menu_id_list, tenant_id=tenant_id)
    return ResponseUtil.success(message=f"成功删除 {deleted_count} 个菜单")


@router.get("/getRouters", summary="获取路由", response_model=List[dict])
async def get_routers(
    current_user: User = Depends(get_current_user),
    db: AsyncSession = Depends(get_db)
):
    """获取路由 - 用于构建前端路由"""
    routers = await menu_service.get_user_routers(db, user_id=current_user.user_id, tenant_id=current_user.tenant_id)
    return routers